package com.education.ai.dao.impl;

import com.education.ai.dao.StudentAnalysisDao;
import com.education.ai.entity.StudentAnalysis;
import com.education.ai.util.JdbcUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 学情分析DAO实现类
 */
@Repository
public class StudentAnalysisDaoImpl implements StudentAnalysisDao {
    
    private static final Logger logger = LoggerFactory.getLogger(StudentAnalysisDaoImpl.class);
    
    @Autowired
    private JdbcUtil jdbcUtil;

    @Override
    public List<StudentAnalysis> findAll() {
        String sql = "SELECT * FROM student_analysis";
        return mapResultsToAnalyses(jdbcUtil.executeQuery(sql));
    }

    @Override
    public Optional<StudentAnalysis> findById(Long id) {
        String sql = "SELECT * FROM student_analysis WHERE id = ?";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql, id);
        return results.isEmpty() ? Optional.empty() : Optional.of(mapRowToAnalysis(results.get(0)));
    }

    @Override
    public List<StudentAnalysis> findByStudentId(String studentId) {
        String sql = "SELECT * FROM student_analysis WHERE student_id = ?";
        return mapResultsToAnalyses(jdbcUtil.executeQuery(sql, studentId));
    }

    @Override
    public StudentAnalysis findByStudentIdAndSubject(String studentId, String subject) {
        String sql = "SELECT * FROM student_analysis WHERE student_id = ? AND subject = ? ORDER BY analyze_time DESC LIMIT 1";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql, studentId, subject);
        return results.isEmpty() ? null : mapRowToAnalysis(results.get(0));
    }

    @Override
    public StudentAnalysis findByStudentIdAndSubjectAndGrade(String studentId, String subject, String grade) {
        String sql = "SELECT * FROM student_analysis WHERE student_id = ? AND subject = ? AND grade = ? ORDER BY analyze_time DESC LIMIT 1";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql, studentId, subject, grade);
        return results.isEmpty() ? null : mapRowToAnalysis(results.get(0));
    }

    @Override
    public List<StudentAnalysis> findByKnowledgeLevel(String knowledgeLevel) {
        String sql = "SELECT * FROM student_analysis WHERE knowledge_level = ?";
        return mapResultsToAnalyses(jdbcUtil.executeQuery(sql, knowledgeLevel));
    }

    @Override
    public List<StudentAnalysis> findBySubject(String subject) {
        String sql = "SELECT * FROM student_analysis WHERE subject = ?";
        return mapResultsToAnalyses(jdbcUtil.executeQuery(sql, subject));
    }

    @Override
    public List<StudentAnalysis> findByGrade(String grade) {
        String sql = "SELECT * FROM student_analysis WHERE grade = ?";
        return mapResultsToAnalyses(jdbcUtil.executeQuery(sql, grade));
    }

    @Override
    public List<StudentAnalysis> findByLearningStyle(String learningStyle) {
        String sql = "SELECT * FROM student_analysis WHERE learning_style LIKE ?";
        return mapResultsToAnalyses(jdbcUtil.executeQuery(sql, "%" + learningStyle + "%"));
    }

    @Override
    public List<StudentAnalysis> findByWeakPoint(String weakPoint) {
        String sql = "SELECT * FROM student_analysis WHERE weak_points LIKE ?";
        return mapResultsToAnalyses(jdbcUtil.executeQuery(sql, "%" + weakPoint + "%"));
    }

    @Override
    public StudentAnalysis save(StudentAnalysis studentAnalysis) {
        if (studentAnalysis.getId() == null) {
            // 插入操作
            String sql = "INSERT INTO student_analysis (student_id, subject, grade, knowledge_level, " +
                    "learning_style, strengths, weak_points, recommendations, analyze_time, " +
                    "learning_attitude, progress_trend, achievement_level, parent_support_level) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            // 设置分析时间
            if (studentAnalysis.getAnalyzeTime() == null) {
                studentAnalysis.setAnalyzeTime(LocalDateTime.now());
            }
            
            long id = jdbcUtil.executeInsert(sql,
                    studentAnalysis.getStudentId(),
                    studentAnalysis.getSubject(),
                    studentAnalysis.getGrade(),
                    studentAnalysis.getKnowledgeLevel(),
                    studentAnalysis.getLearningStyle(),
                    studentAnalysis.getStrengths(),
                    studentAnalysis.getWeakPoints(),
                    studentAnalysis.getRecommendations(),
                    studentAnalysis.getAnalyzeTime(),
                    studentAnalysis.getLearningAttitude(),
                    studentAnalysis.getProgressTrend(),
                    studentAnalysis.getAchievementLevel(),
                    studentAnalysis.getParentSupportLevel());
            
            studentAnalysis.setId(id);
            return studentAnalysis;
        } else {
            // 更新操作
            update(studentAnalysis);
            return studentAnalysis;
        }
    }

    @Override
    public boolean update(StudentAnalysis studentAnalysis) {
        String sql = "UPDATE student_analysis SET student_id = ?, subject = ?, grade = ?, " +
                "knowledge_level = ?, learning_style = ?, strengths = ?, weak_points = ?, " +
                "recommendations = ?, analyze_time = ?, learning_attitude = ?, " +
                "progress_trend = ?, achievement_level = ?, parent_support_level = ? " +
                "WHERE id = ?";
        
        int rows = jdbcUtil.executeUpdate(sql,
                studentAnalysis.getStudentId(),
                studentAnalysis.getSubject(),
                studentAnalysis.getGrade(),
                studentAnalysis.getKnowledgeLevel(),
                studentAnalysis.getLearningStyle(),
                studentAnalysis.getStrengths(),
                studentAnalysis.getWeakPoints(),
                studentAnalysis.getRecommendations(),
                studentAnalysis.getAnalyzeTime(),
                studentAnalysis.getLearningAttitude(),
                studentAnalysis.getProgressTrend(),
                studentAnalysis.getAchievementLevel(),
                studentAnalysis.getParentSupportLevel(),
                studentAnalysis.getId());
        
        return rows > 0;
    }

    @Override
    public boolean deleteById(Long id) {
        String sql = "DELETE FROM student_analysis WHERE id = ?";
        int rows = jdbcUtil.executeUpdate(sql, id);
        return rows > 0;
    }

    @Override
    public long count() {
        String sql = "SELECT COUNT(*) AS count FROM student_analysis";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql);
        if (!results.isEmpty()) {
            return ((Number) results.get(0).get("count")).longValue();
        }
        return 0;
    }
    
    /**
     * 将查询结果映射为学情分析对象列表
     */
    private List<StudentAnalysis> mapResultsToAnalyses(List<Map<String, Object>> results) {
        List<StudentAnalysis> analyses = new ArrayList<>();
        for (Map<String, Object> row : results) {
            analyses.add(mapRowToAnalysis(row));
        }
        return analyses;
    }
    
    /**
     * 将单行结果映射为学情分析对象
     */
    private StudentAnalysis mapRowToAnalysis(Map<String, Object> row) {
        StudentAnalysis analysis = new StudentAnalysis();
        
        analysis.setId(((Number) row.get("id")).longValue());
        analysis.setStudentId((String) row.get("student_id"));
        analysis.setSubject((String) row.get("subject"));
        analysis.setGrade((String) row.get("grade"));
        analysis.setKnowledgeLevel((String) row.get("knowledge_level"));
        analysis.setLearningStyle((String) row.get("learning_style"));
        analysis.setStrengths((String) row.get("strengths"));
        analysis.setWeakPoints((String) row.get("weak_points"));
        analysis.setRecommendations((String) row.get("recommendations"));
        
        if (row.get("analyze_time") != null) {
            analysis.setAnalyzeTime(jdbcUtil.convertToLocalDateTime(row.get("analyze_time")));
        }
        
        if (row.get("learning_attitude") != null) {
            analysis.setLearningAttitude((String) row.get("learning_attitude"));
        }
        
        if (row.get("progress_trend") != null) {
            analysis.setProgressTrend((String) row.get("progress_trend"));
        }
        
        if (row.get("achievement_level") != null) {
            analysis.setAchievementLevel((String) row.get("achievement_level"));
        }
        
        if (row.get("parent_support_level") != null) {
            analysis.setParentSupportLevel((String) row.get("parent_support_level"));
        }
        
        return analysis;
    }
} 